package hotgammon.domain;

import java.util.*;

public class BoardImp implements Board {

	private BoardLocation[] bl;
	private Location[] locations = Location.values();
		
	/**
			{Location.B1, Location.B2, Location.B3, Location.B4, Location.B5, Location.B6, 
			Location.B7, Location.B8, Location.B9, Location.B10, Location.B11, Location.B12, 
			Location.R1, Location.R2, Location.R3, Location.R4, Location.R5, Location.R6, 
			Location.R7, Location.R8, Location.R9, Location.R10, Location.R11, Location.R12, 
			Location.B_BAR, Location.B_BEAR_OFF, Location.R_BAR, Location.R_BEAR_OFF};
	*/
		
	public BoardImp() {
		reset();
	}
	
	public void reset() {
		bl = new BoardLocation[locations.length];
		for(int i = 0; i < locations.length ; i++) {
			int k = 0;
			Location l = locations[i];
			Color color = null;
			
			switch(l) {
				case R1:
					k = 2;
					color = Color.BLACK;
					break;
				case B1:
					k = 2;
					color = Color.RED;
					break;
				case R6:
					k = 5;
					color = Color.RED;
					break;
				case B6:
					k = 5;
					color = Color.BLACK;
					break;
				case R8:
					k = 3;
					color = Color.RED;
					break;
				case B8:
					k = 3;
					color = Color.BLACK;
					break;
				case R12:
					k = 5;
					color = Color.BLACK;
					break;
				case B12:
					k = 5;
					color = Color.RED;
					break;
				default:
					k = 0;
					color = Color.NONE;
					break;
			}
				
			bl[i] = new BoardLocation(l, k, color);
		}
	}
	
	public void move(Location from, Location to) {
		BoardLocation BLfrom = getBoardLocation(from);
		BoardLocation BLto = getBoardLocation(to);
		Color color = BLfrom.getColor();
		
		int checkersFrom = BLfrom.getCheckers();
		if(checkersFrom - 1 == 0)
			BLfrom.setColor(Color.NONE);
		
		int checkersTo = BLto.getCheckers();
		if(checkersTo == 0)
			BLto.setColor(color);
		
		BLfrom.setCheckers(checkersFrom - 1);
		BLto.setCheckers(checkersTo + 1);
	}
	
	private BoardLocation getBoardLocation(Location l) {
		BoardLocation b = null;
		for(BoardLocation k: bl) {
			if(k.getLocation() == l) {
				b = k;
				break;
			}
		}
		
		return b;
	}
	
	public Color getColor(Location l) {
		BoardLocation b = getBoardLocation(l);
		return b.getColor();
	}
	
	public int getCount(Location l) {
		BoardLocation b = getBoardLocation(l);
		return b.getCheckers();
	}
	
	public Iterator<Location> iterator() {
		return Arrays.asList(locations).iterator();
	}
}
